<template>
  <el-container>
    <el-header><NavBar></NavBar></el-header>
    <el-main
      ><el-row>
        <el-col :md="14"
          ><div class="register-container">
            <el-card class="box-card">
              <div class="title-container">
                <span>账号注册</span>
              </div>
              <el-form
                label-position="left"
                :model="registerForm"
                :rules="rules"
                ref="registerForm"
                label-width="100px"
                class="demo-registerForm"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="registerForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    show-password
                    v-model="registerForm.password"
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="check_pwd">
                  <el-input
                    show-password
                    v-model="registerForm.check_pwd"
                  ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="registerForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-input
                    class="sort-input"
                    v-model.number="registerForm.code"
                  ></el-input>
                  <el-button
                    :disabled="!isRightPhone"
                    @click="sendMsg"
                    type="primary"
                    >{{sendBtnTxt}}</el-button
                  >
                </el-form-item>
                <el-form-item label="邀请码" prop="invite_code">
                  <el-input
                    class="sort-input"
                    v-model="registerForm.invite_code"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('registerForm')"
                    >注册</el-button
                  >
                  <el-button @click="resetForm('registerForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div></el-col
        >
        <el-col :md="10" class="hidden-sm-and-down">
          <div class="img-box">
            <el-image :src="require('@/assets/invite.png')"></el-image>
          </div>
        </el-col> </el-row
    ></el-main>
  </el-container>
</template>

<script>
import { mapActions } from "vuex";
import "element-ui/lib/theme-chalk/display.css";
import NavBar from "@/components/NavBar";
export default {
  name: "Register",
  components: {
    NavBar,
  },
  data() {
    // 自定义用户名校验器
    var checkUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        if (value.length > 10) {
          callback(new Error("用户名不能超过10个字符"));
        } else {
          callback();
        }
      }, 500);
    };
    // 密码自定义校验器
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.checkPass !== "") {
          this.$refs.registerForm.validateField("check_pwd");
        }
        callback();
      }
    };
    // 确认密码自定义校验器
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    // 校验手机号的验证器
    var checkphone = (rule, value, callback) => {
      this.isRightPhone = false;
      if (value === "") {
        callback(new Error("手机号不能为空"));
      }
      setTimeout(() => {
        const regPhone = /^1[3|5|7|8][0-9]{9}$/;
        // 判断是否是合法的手机号
        if (regPhone.test(value)) {
          this.checkPhone({ phone: value }).then((res) => {
            this.isRightPhone = true;
            callback();
          });
        } else {
          callback(new Error("手机号格式不正确"));
        }
      }, 500);
    };
    return {
      // 注册表单绑定的数据
      registerForm: {
        username: "",
        password: "",
        check_pwd: "",
        phone: "",
        code: "",
        invite_code: "",
      },
      // 是否是正确的手机号码
      isRightPhone: false,
      // 发送验证码按钮的文字
      sendBtnTxt:'发送验证码',
      // 表单有验证规则
      timer:null,
      conter:10,
      rules: {
        username: [{ validator: checkUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        check_pwd: [{ validator: validatePass2, trigger: "blur" }],
        phone: [{ validator: checkphone, trigger: "blur" }],
        code: [
          { required: true, message: "验证码不能为空" },
          { type: "number", message: "必须为数字" },
        ],
      },
    };
  },
  methods: {
    ...mapActions({
      register: "user/register",
      checkPhone: "user/checkPhone",
      getSmsCode: "user/getSmsCode",
    }),
    // 发送验证码
    sendMsg() {
      this.isRightPhone = false
      this.getSmsCode({ phone: this.registerForm.phone }).then((res) => {
        this.$notify({
          title: "验证码",
          message: res.smsCode,
          type: "success",
        });
        this.countDown()
      }).catch(err =>{
        this.isRightPhone = true
      })
    },
    // 倒计时开始
    countDown(){
      this.timer = setInterval(() => {
        this.sendBtnTxt = `${this.conter}秒`
        this.conter--;
        if(this.conter < 0){
          this.reset()
        }
      }, 1000);
    },
    // 重置计时器
    reset(){
      this.isRightPhone = true
      this.sendBtnTxt = '发送验证码'
      if(this.timer){
        clearInterval(this.timer)
        this.conter = 10;
        this.timer = null
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.register(this.registerForm).then((res) => {
            this.$message({
              message: "注册成功，即将跳转到登录",
              type: "success",
            });
            setTimeout(() => {
              this.$router.push('/login')
            }, 2000);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.reset()
      this.isRightPhone = false
    },
  },
};
</script>

<style lang="scss" scoped>
.register-container {
  border-right: 1px solid rgb(175, 175, 175);
  height: 100%;
  width: 100%;
  padding-top: 150px;

  .box-card {
    min-height: 500px;
    max-width: 450px;
    margin: 0px auto;

    .title-container {
      text-align: center;
      font-size: 26px;
      font-weight: bold;
      margin-bottom: 15px;
    }

    .sort-input {
      width: 80px;
      margin-right: 15px;
    }
  }
}

.el-row {
  height: 100%;
  .el-col {
    height: 100%;
  }
}

.el-main {
  background-color: #e9eef3;

  .img-box {
    padding: 150px 50px;
  }
}
</style>